using Admin2505.Domain.Common;
using Admin2505.Domain.Entityes;
using Admin2505.Iinfrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace Admin2505.Domain.Reposoitories;
//实现通用接口
public class EfRepository<T> : IRepository<T> where T:EntityBase
{
    private readonly Admin2505DbContext _db;

    private readonly DbSet<T> _tb;

    public EfRepository(Admin2505DbContext db)
    {
        _db=db;
        _tb = _db.Set<T>();
    }


    async Task<IEnumerable<T>> IRepository<T>.GetAllAsync()
    {
        var list = await _tb.AsNoTracking().ToListAsync();
        return list;
    }

    public async Task<T?> GetByIdAsync(Guid id)
    {
        var obj = await _tb.FindAsync(id);
        return obj;
    }

    async Task<T> IRepository<T>.CreateAsync(T entity)
    {
        var obj = await _tb.AddAsync(entity);
        await _db.SaveChangesAsync();
        return obj.Entity;
    }

    async Task IRepository<T>.UpdateAsync(T entity)
    {
        entity.UpdatedAt = DateTime.UtcNow;
        _tb.Update(entity);
        await _db.SaveChangesAsync();
    }

    public async Task DeleteAsync(T entity)
    {
        _tb.Remove(entity);
        await _db.SaveChangesAsync();
        // 硬删除

        // // 软删除
        // entity.IsActived= true;
        // await UpdateAsync(entity);
        
    }

    public async Task DeleteAsync(Guid id)
    {
        var obj = await GetByIdAsync(id);
        if (obj==null)
        {
            return;
        }
        await DeleteAsync(obj);
    }

    public async Task<PageResultDto<T>> GetPagedAsync(int PageIndex, int PageSize)
    {
       var list = await _tb.AsNoTracking()
       .Skip((PageIndex-1)*PageSize)
       .Take(PageSize)
       .ToListAsync();


       var count = await _tb.CountAsync();
       var PageResult = new PageResultDto<T> { Items=list,Totalcoun= count};
       return PageResult;
    }
}